package com.learn.english.service.impl;

import com.learn.english.domain.PageQueryDTO;
import com.learn.english.domain.R;
import com.learn.english.enums.ResultCode;
import com.learn.english.mapper.UserMapper;
import com.learn.english.model.entity.User;
import com.learn.english.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author TISNIW
 * @version 1.0
 * @date 2025/6/16 11:14
 * @desc 用户服务实现类
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 获取用户总数
     */
    @Override
    public Long getUserCount() {
        return userMapper.queryUserCount().longValue();
    }

    /**
     * 分页查询用户列表
     */
    @Override
    public R getUserList(PageQueryDTO queryDTO) {
        try {
            // 查询总记录数
            Integer total = userMapper.queryUserCount();
            
            // 查询分页数据
            List<User> userList = userMapper.queryUserListByPage(
                    queryDTO.getOffset(), queryDTO.getPageSize());
            
            // 封装结果
            Map<String, Object> result = new HashMap<>();
            result.put("total", total);
            result.put("list", userList);
            result.put("pageNum", queryDTO.getPageNum());
            result.put("pageSize", queryDTO.getPageSize());
            
            return R.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(ResultCode.FAIL);
        }
    }

    /**
     * 根据ID获取用户详情
     */
    @Override
    public R getUserDetail(Long id) {
        try {
            User user = userMapper.queryById(id.intValue());
            if (user == null) {
                return R.fail(ResultCode.USER_NOT_FOUND);
            }
            // 隐藏敏感信息
            user.setPassword(null);
            return R.ok(user);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(ResultCode.FAIL);
        }
    }

    /**
     * 添加用户
     */

    @Override
    public R addUser(User user) {
        try {
            // 校验用户名是否已存在
            if (userMapper.queryByUsername(user.getUsername()) != null) {
                return R.fail(ResultCode.USERNAME_EXIST);
            }
            
            // 校验邮箱是否已存在
            if (StringUtils.isNotEmpty(user.getEmail()) && 
                userMapper.queryByEmail(user.getEmail()) != null) {
                return R.fail(ResultCode.EMAIL_EXIST);
            }
            
            // 设置默认值
            user.setUid(generateUniqueUid());
            user.setCreatedAt(LocalDateTime.now());
            user.setUpdatedAt(LocalDateTime.now());
            user.setIsDeleted((byte) 0);
            user.setStatus((byte) 1); // 默认启用
            user.setLoginCount(0);
            
            // 保存用户
            Integer result = userMapper.addUser(user);
            if (result > 0) {
                return R.ok();
            } else {
                return R.fail(ResultCode.USER_CREATE_FAILED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(ResultCode.FAIL);
        }
    }

    /**
     * 更新用户信息
     */

    @Override
    public R updateUser(User user) {
        try {
            // 校验用户是否存在
            User existingUser = userMapper.queryById(user.getId().intValue());
            if (existingUser == null) {
                return R.fail(ResultCode.USER_NOT_FOUND);
            }
            
            // 设置更新时间
            user.setUpdatedAt(LocalDateTime.now());
            
            // 更新用户信息
            Integer result = userMapper.updateUser(user);
            if (result > 0) {
                return R.ok();
            } else {
                return R.fail(ResultCode.USER_UPDATE_FAILED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(ResultCode.FAIL);
        }
    }

    /**
     * 更新用户状态
     */

    @Override
    public R updateUserStatus(Long id, Byte status) {
        try {
            // 校验用户是否存在
            User user = userMapper.queryById(id.intValue());
            if (user == null) {
                return R.fail(ResultCode.USER_NOT_FOUND);
            }
            
            // 更新状态
            user.setStatus(status);
            user.setUpdatedAt(LocalDateTime.now());
            
            Integer result = userMapper.updateUser(user);
            if (result > 0) {
                return R.ok();
            } else {
                return R.fail(ResultCode.USER_STATUS_UPDATE_FAILED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(ResultCode.FAIL);
        }
    }

    /**
     * 重置用户密码
     */

    @Override
    public R resetPassword(Long id, String newPassword) {
        try {
            // 校验用户是否存在
            User user = userMapper.queryById(id.intValue());
            if (user == null) {
                return R.fail(ResultCode.USER_NOT_FOUND);
            }
            
            // 更新密码
            Integer result = userMapper.updatePassword(id.intValue(), newPassword);
            if (result > 0) {
                return R.ok();
            } else {
                return R.fail(ResultCode.PASSWORD_UPDATE_FAILED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(ResultCode.FAIL);
        }
    }

    /**
     * 删除用户
     */

    @Override
    public R deleteUser(Long id) {
        try {
            // 校验用户是否存在
            User user = userMapper.queryById(id.intValue());
            if (user == null) {
                return R.fail(ResultCode.USER_NOT_FOUND);
            }
            
            // 软删除用户
            Integer result = userMapper.softDeleteUser(id.intValue());
            if (result > 0) {
                return R.ok();
            } else {
                return R.fail(ResultCode.USER_DELETE_FAILED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(ResultCode.FAIL);
        }
    }

    /**
     * 批量删除用户
     */

    @Override
    public R batchDeleteUsers(List<Long> ids) {
        try {
            for (Long id : ids) {
                if (userMapper.queryById(id.intValue()) == null) {
                    continue;
                }
                userMapper.softDeleteUser(id.intValue());
            }
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(ResultCode.FAIL);
        }
    }

    /**
     * 批量更新用户状态
     */

    @Override
    public R batchUpdateUserStatus(List<Long> ids, Byte status) {
        try {
            for (Long id : ids) {
                User user = userMapper.queryById(id.intValue());
                if (user != null) {
                    user.setStatus(status);
                    user.setUpdatedAt(LocalDateTime.now());
                    userMapper.updateUser(user);
                }
            }
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(ResultCode.FAIL);
        }
    }

    /**
     * 根据条件搜索用户
     */
    @Override
    public R searchUsers(PageQueryDTO queryDTO) {
        try {
            // 根据条件查询用户列表
            List<User> userList = userMapper.queryUsersByCondition(
                    StringUtils.defaultString(queryDTO.getUid(), ""),
                    StringUtils.defaultString(queryDTO.getRole(), ""),
                    Integer.valueOf(queryDTO.getStatus() != null ? queryDTO.getStatus() : 0)
            );
            
            // 封装结果
            Map<String, Object> result = new HashMap<>();
            result.put("total", userList.size());
            result.put("list", userList);
            result.put("pageNum", queryDTO.getPageNum());
            result.put("pageSize", queryDTO.getPageSize());
            
            return R.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(ResultCode.FAIL);
        }
    }

    /**
     * 生成唯一的UID
     */
    private String generateUniqueUid() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 20);
    }
}
